package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.api.domain.StatsValue;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbCompanyMapper;
import com.zfei.gfb.dao.GfbJobMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbCompany;
import com.zfei.gfb.model.GfbGoods;
import com.zfei.gfb.model.GfbJob;
import com.zfei.gfb.query.GfbJobQuery;
import com.zfei.gfb.request.*;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.util.gson.Types;
import com.zfei.gfb.vo.GfbGoodsVo;
import com.zfei.gfb.vo.GfbHouseVo;
import com.zfei.gfb.vo.GfbJobListVo;
import com.zfei.gfb.vo.GfbJobVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 */
@Api(tags = "H5岗位接口")
@RestController
@RequestMapping("/h5/job")
public class H5JobController {

    @Resource
    private GfbJobMapper gfbJobMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private GfbCompanyMapper gfbCompanyMapper;

    @Resource
    private StatsService statsService;

    @Auth(type = Const.COMPANY)
    @ApiOperation(value = "我发布的岗位")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobListVo.class),
    })
    @LogResult
    @HttpJson("/my/list")
    public Object listMy(@RequestBody GfbJobQuery query) {
        query.check().build(Now::millis);
        GfbCompany company = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);

        query.setUserId(company.getId());
        query.setType(Const.JOB_COM);

        GfbJobListVo result = new GfbJobListVo();


        List<GfbJob> records = gfbJobMapper.list(query);
        List<GfbJobVo> vos = Beans.copys(records, GfbJobVo.class);

        vos.forEach(vo ->
        {
            String ext = vo.getExt();
            String from;
            if (StringUtils.isBlank(ext)) {
                from = "client";
            } else {
                H5JobWantedController.JobExt jobExt = Gsons.fromJson(ext, H5JobWantedController.JobExt.class);
                if (jobExt.getFrom() != null) {
                    from = jobExt.getFrom();
                    vo.setSettleMethod(jobExt.getSettleMethod());
                } else {
                    from = "client";
                }
            }
            vo.setFrom(from);
            vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_BROWSE_COUNT).getNum());
        });

        result.setData(vos);
        return result;

    }

    @Auth(type = Const.COMPANY)
    @ApiOperation(value = "发布岗位")
    @LogResult
    @HttpJson("/my/add")
    public Object addMy(@RequestBody H5JobAddRequest request) {

        request.checkInsertNull();

        GfbCompany com = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);
        GfbCompany company = gfbCompanyMapper.selectByPrimaryKey(com.getId());

        if (company.getAudit() != Const.COMPANY_AUTH_SUCCESS) {
            throw new StatusException(Status.NOT_ALLOWED, "账号未认证通过");
        }
        if (company.getStatus() == Const.STATUS_OFF) {
            throw new StatusException(Status.NOT_ALLOWED, "账号已被禁用");
        }

        GfbJob record = Beans.copy(request, GfbJob.class);
        record.setUserId(company.getId());
        record.setUserName(company.getName());
        record.setType(Const.JOB_COM);
        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "client");
        ext.put("settleMethod", request.getSettleMethod());
        record.setExt(Gsons.toJson(ext));
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());
        record.setPubTime(Now.millis());
        record.setStatus(Const.STATUS_ON);

        gfbJobMapper.insertSelective(record);
        return null;
    }

    @Auth(type = Const.COMPANY)
    @ApiOperation(value = "编辑岗位")
    @LogResult
    @HttpJson("/my/edit")
    public Object editMy(@RequestBody GfbJobEditRequest request) {

        request.checkUpdateNull();

        GfbCompany com = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);
        GfbCompany company = gfbCompanyMapper.selectByPrimaryKey(com.getId());

        if (company.getAudit() != Const.COMPANY_AUTH_SUCCESS) {
            throw new StatusException(Status.NOT_ALLOWED, "账号未认证通过");
        }
        if (company.getStatus() == Const.STATUS_OFF) {
            throw new StatusException(Status.NOT_ALLOWED, "账号已被禁用");
        }

        GfbJob record = gfbJobMapper.selectByPrimaryKey(request.getId());
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        if (!record.getUserId().equals(company.getId()) || record.getType() != Const.JOB_COM) {
            throw new StatusException(Status.NOT_ALLOWED);
        }

        BeanUtils.copyProperties(request, record);
        record.setUpdateTime(Now.millis());
        record.setPubTime(Now.millis());
        gfbJobMapper.updateByPrimaryKeySelective(record);

        return null;
    }

    @Auth(type = Const.COMPANY)
    @ApiOperation(value = "删除岗位")
    @LogResult
    @HttpJson("/my/del")
    public Object delMy(@RequestBody GfbDelRequest request) {
        request.checkDelNull();
        Integer id = request.getId();

        GfbJob record = gfbJobMapper.selectByPrimaryKey(id);
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        GfbCompany company = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);
        if (!record.getUserId().equals(company.getId()) || record.getType() != Const.JOB_COM) {
            throw new StatusException(Status.NOT_ALLOWED);
        }

        gfbJobMapper.deleteByPrimaryKey(id);
        return null;
    }


    @ApiOperation(value = "岗位信息2-3-1")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbJobQuery query) {

        query.check().build(Now::millis);
        GfbJobListVo result = new GfbJobListVo();

        int total = gfbJobMapper.totalH5(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }
        GfbCompany company = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);
        if (company != null) {
            if (query.getType() != null && query.getType() == Const.JOB_COM) {
                query.setUserId(company.getId());
            }
        }

        List<GfbJob> records = gfbJobMapper.listH5(query);
        List<GfbJobVo> vos = Beans.copys(records, GfbJobVo.class);
        vos.forEach(vo ->
        {
            String ext = vo.getExt();
            String from;
            if (StringUtils.isBlank(ext)) {
                from = "client";
            } else {
                H5JobWantedController.JobExt jobExt = Gsons.fromJson(ext, H5JobWantedController.JobExt.class);
                if (jobExt.getFrom() != null) {
                    from = jobExt.getFrom();
                    vo.setSettleMethod(jobExt.getSettleMethod());
                } else {
                    from = "client";
                }
            }
            vo.setFrom(from);
            vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_BROWSE_COUNT).getNum());
        });
        result.setData(vos);
        return result;

    }

    @ApiOperation(value = "岗位详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbJob record = gfbJobMapper.selectByPrimaryKey(id);

        GfbJobVo vo = Beans.copy(record, GfbJobVo.class);
        String ext = vo.getExt();
        String from;
        if (StringUtils.isBlank(ext)) {
            from = "client";
        } else {
            H5JobWantedController.JobExt jobExt = Gsons.fromJson(ext, H5JobWantedController.JobExt.class);
            if (jobExt.getFrom() != null) {
                from = jobExt.getFrom();
                vo.setSettleMethod(jobExt.getSettleMethod());
            } else {
                from = "client";
            }
        }

        StatsValue postStats = new StatsValue(record.getId().toString(), StatsTag.JOB_BROWSE_COUNT, 1);
        statsService.inc(postStats);
        vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_BROWSE_COUNT).getNum());
        vo.setFrom(from);
        return vo;
    }
}
